<?php
// ========================== 文件说明 ==========================//
// 本文件说明：前后台公共操作
// --------------------------------------------------------------//
// 本程序作者：angel
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Ver 1.6
// --------------------------------------------------------------//
// 本程序主页：http://www.sablog.net
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

error_reporting(7);
set_magic_quotes_runtime(0);
header("content-Type: text/html; charset=UTF-8");
$mtime = explode(' ', microtime());
$starttime = $mtime[1] + $mtime[0];

define('SABLOG_ROOT', substr(dirname(__FILE__), 0, -7));
define('MODULE_DIR', SABLOG_ROOT.'modules/');

require_once(SABLOG_ROOT.'include/sax_version.php');

// 加载核心函数
require_once(SABLOG_ROOT.'include/func/global.func.php');

$action = addslashes($_GET['action'] ? $_GET['action'] : $_POST['action']);
$php_self = char_cv($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
$timestamp = time();
//登陆存活期一个月
$login_life = 2592000;

// 防止 PHP 5.1.x 使用时间函数报错
if(PHP_VERSION > '5.1') {
	@date_default_timezone_set('UTC');
}

define('IS_ROBOT', isrobot());
$referer = getreferer();

// 加载数据库配置信息
require_once(SABLOG_ROOT.'config.php');

// 检查防刷新或代理访问
if($attackevasive) {
	require_once(SABLOG_ROOT.'include/fense.inc.php');
}
// 加载数据库类
require_once(SABLOG_ROOT.'include/class/mysql.class.php');
// 初始化数据库类
$DB = new DB_MySQL;
$DB->connect($servername, $dbusername, $dbpassword, $dbname, $usepconnect);
unset($servername, $dbusername, $dbpassword, $dbname, $usepconnect);

// 获得IP地址
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
	$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
	$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
	$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
	$onlineip = $_SERVER['REMOTE_ADDR'];
}
$onlineip = char_cv($onlineip);
@preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
unset($onlineipmatches);

// 读取缓存
if (!@include(SABLOG_ROOT.'cache/cache_settings.php')) {
	require_once(SABLOG_ROOT.'include/func/cache.func.php');
	rethestats('settings');
	exit('<p>Settings caches successfully created, please refresh.</p>');
}

// 检查gzip加速支持情况
if ($options['gzipcompress'] && extension_loaded('zlib')) {
	@ob_start('ob_gzhandler');
} else {
	$options['gzipcompress'] = 0;
	ob_start();
}
!$options['templatename'] && $options['templatename'] = 'default';
$options['title'] = $options['name'];
$timeoffset = (!$options['server_timezone'] || $options['server_timezone'] == '111') ? 0 : $options['server_timezone'];

// 系统URL
if (!$options['url']) {
	//HTTP_HOST已经包含端口信息,不必加SERVER_PORT了.
	$options['url'] = 'http://'.char_cv($_SERVER['HTTP_HOST']).substr($php_self,0,strrpos($php_self,'/')).'/';
} else {
	$options['url'] = str_replace(array('{host}','index.php'), array(char_cv($_SERVER['HTTP_HOST']),''), $options['url']);
	if (substr($options['url'], -1) != '/') {
		$options['url'] = $options['url'].'/';
	}
}

$cachelost  = '';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_statistics.php') ? '' : 'statistics,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_newcomments.php') ? '' : 'newcomments,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_categories.php') ? '' : 'categories,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_archives.php') ? '' : 'archives,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_hottags.php') ? '' : 'hottags,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_links.php') ? '' : 'links,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_stylevars.php') ? '' : 'stylevars,';
$cachelost .= (@include SABLOG_ROOT.'cache/cache_latestpub.php') ? '' : 'latestpub,';

if($cachelost) {
	require_once(SABLOG_ROOT.'include/func/permalink.func.php');
	require_once(SABLOG_ROOT.'include/func/cache.func.php');
	$cachelost = explode(',',$cachelost);
	echo '<p>Cache List:</p><p>';
	foreach ($cachelost as $name) {
		if($name) {
			rethestats($name);
			echo $name.'<br />';
		}
	}
	exit('</p><p>Caches successfully created, please refresh.</p>');
}

//更新在线人数
if ($options['enable_stat'] && $stats_expire < $timestamp) {
	$stats['online_user'] = $DB->result($DB->query("SELECT COUNT(hash) FROM {$db_prefix}sessions WHERE is_robot='0'"), 0);
	$stats['online_robot'] = $DB->result($DB->query("SELECT COUNT(hash) FROM {$db_prefix}sessions WHERE is_robot='1'"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET online_user = '".$stats['online_user']."', online_robot = '".$stats['online_robot']."'");
	require_once(SABLOG_ROOT.'include/func/cache.func.php');
	rethestats('statistics');
}

// 将缓存中的转义字符去掉
$options = sax_stripslashes($options);
$linkcache = sax_stripslashes($linkcache);
$catecache = sax_stripslashes($catecache);
if ($stylevar) {
	$stylevar = sax_stripslashes($stylevar);
}
$newcommentcache = sax_stripslashes($newcommentcache);
$page = intval($_GET['page']);

// 允许程序在 register_globals = off 的环境下工作
$onoff = function_exists('ini_get') ? ini_get('register_globals') : get_cfg_var('register_globals');
if ($onoff != 1) {
	@extract($_POST, EXTR_SKIP);
	@extract($_GET, EXTR_SKIP);
	@extract($_COOKIE, EXTR_SKIP);
}

// 判断 magic_quotes_gpc 状态
if (@get_magic_quotes_gpc()) {
    $_GET = sax_stripslashes($_GET);
    $_POST = sax_stripslashes($_POST);
    $_COOKIE = sax_stripslashes($_COOKIE);
}

$sax_auth_key = md5($onlineip.$_SERVER['HTTP_USER_AGENT']);
list($sax_uid, $sax_pw, $sax_logincount) = $_COOKIE['sax_auth'] ? explode("\t", authcode($_COOKIE['sax_auth'], 'DECODE')) : array('', '', '');
$sax_hash = sax_addslashes($_COOKIE['sax_hash']);

$sax_uid = intval($sax_uid);
$sax_pw = sax_addslashes($sax_pw);
$sax_logincount = intval($sax_logincount);
$sax_group = 4;

$seccode = $sessionexists = 0;
$userfields = 'u.userid AS sax_uid, u.username AS sax_user, u.password AS sax_pw, u.groupid AS sax_group, u.logincount AS sax_logincount, u.email as sax_email, u.url as sax_url, u.lastpost, u.lastip, u.lastvisit, u.lastactivity';
if ($sax_hash) {
	if ($sax_uid && $sax_pw) {
		$query = $DB->query("SELECT s.hash, s.seccode, $userfields
			FROM {$db_prefix}users u
			LEFT JOIN {$db_prefix}sessions s ON (s.uid = u.userid)
			WHERE s.hash='$sax_hash' AND u.userid='$sax_uid' AND CONCAT_WS('.',s.ip1,s.ip2,s.ip3,s.ip4)='$onlineip'
			AND u.password='$sax_pw' AND u.logincount='$sax_logincount' AND s.auth_key='$sax_auth_key'");
	} else {
		$query = $DB->query("SELECT hash,uid as sessionuid,groupid,seccode,lastactivity FROM {$db_prefix}sessions WHERE hash='$sax_hash' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip' LIMIT 1");
	}
	if ($_EVO = $DB->fetch_array($query)){
		$sessionexists = 1;
		if($_EVO['sessionuid']) {
			$query = $DB->query("SELECT $userfields FROM {$db_prefix}users u WHERE u.userid='".intval($_EVO['sessionuid'])."'");
			$_EVO = array_merge($_EVO, $DB->fetch_array($query));
			$sax_uid = $_EVO['userid'];
		}
	} else {
		if($_EVO = $DB->fetch_one_array("SELECT hash,groupid,seccode,lastactivity FROM {$db_prefix}sessions WHERE hash='$sax_hash' AND CONCAT_WS('.',ip1,ip2,ip3,ip4)='$onlineip'")) {
			dcookies();
			$sessionexists = 1;
		}
	}
}
if(!$sessionexists) {
	if($sax_uid) {
		if(!($_EVO = $DB->fetch_one_array("SELECT $userfields FROM {$db_prefix}users u WHERE u.userid='$sax_uid' AND u.password='$sax_pw'"))) {
			dcookies();
		}
	}
	!$sax_hash && $sax_hash = random(6);
	!$seccode && $seccode = random(4, 1);
}
$userfields = '';
@extract($_EVO);

$lastvisit = !$lastvisit ? $timestamp : $lastvisit;

if ($sax_group == 1) {
	error_reporting(7);
}
if(!$_COOKIE['sax_hash'] || $sax_hash != $_COOKIE['sax_hash']) {
	scookie('sax_hash', $sax_hash, 604800);
}


$formhash = formhash();
/*
if ($options['active_plugins']) {
	//如果设置了插件
	$plugins = unserialize($options['active_plugins']);
	if (is_array($plugins)) {
		//遍历插件名字
		foreach ($plugins as $key => $plugin) {
			//存在并且不包含..才包含文件
			if ($plugin && file_exists(SABLOG_ROOT.'plugins/'.$plugin) && strpos($plugin,'..')===false) {
				include_once(SABLOG_ROOT.'plugins/'.$plugin);
			} else {
				//否则删除插件纪录
				unset($plugins[$key]);
				if ($plugins){
					$plugins = sax_addslashes(serialize($plugins));
				}
				require_once(SABLOG_ROOT.'include/func/cache.func.php');
				$DB->query("REPLACE INTO {$db_prefix}settings VALUES ('active_plugins', '$plugins')");
				settings_recache();
			}
		}
	}
}
print_r($_GET);
echo '<hr>';
print_r($_POST);
echo '<hr>';
print_r($_REQUEST);

*/

// 头像调用设置
if ($options['avatar_default'] == 'blank') {
	$options['avatar_default'] = $options['url'].'images/gravatar.png';
}

// 调试函数
function pr($a) {
	echo '<pre>';
	print_r($a);
	echo '</pre>';
}
?>